package com.demo.springbooot_demo.filter;

import com.demo.springbooot_demo.pojo.LoginUser;
import com.demo.springbooot_demo.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import com.demo.springbooot_demo.utils.TokenManager;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException,RuntimeException {

        //获取token
        String token = request.getHeader("token");
        //不存在token,放行让后面的过滤器来判断为未认证用户抛出异常
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return ;
        }
        //解析token
        String userid;
        try {
        Claims claims = TokenManager.decodeToken(token);
            userid = claims.getSubject();
        }catch (Exception e){
            e.printStackTrace();
            throw new BadCredentialsException("非法token");
        }
        //从缓存获取用户信息
        // 从 Redis 中获取存储的对象
        LoginUser user = redisCache.getCacheObject("demo-user:" + userid);
        System.out.println(user.getUser().getUserName());
        if(Objects.isNull(user)){
            throw new  BadCredentialsException("用户未登录");
        }
        //存入SecurityContextHolder 更改认证状态
        //todo authenticationToken中没有权限集合信息（authorities）
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user,null,null);//用三个参数的构造才会改认证状态为已认证
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);
        return;
    }
}
